/*

* ------------------------------------------------------------------------
* ------------------------------------------------------------------------
* |     Smart-Shop开源商城系统/ Java商城-首选电商平台系统 请务必保留此注释头信息
* |     开源地址: https://gitee.com/ningbo-qishan/gruul-mall
* ------------------------------------------------------------------------
* ------------------------------------------------------------------------
* |     可正常分享和学习源码,未经授权 不可商用！
* |     商业版中台购买/开源版商业授权 联系技术客服
* |     官网:  https://www.73app.cn/
* ------------------------------------------------------------------------
* ------------------------------------------------------------------------
* |     Copyright (c) 2016-2999 宁波启山智软科技有限公司
* |     版权所有 ,侵权必究！
* ------------------------------------------------------------------------

*/
package com.medusa.gruul.common.core.auth.client.interceptor;


import cn.hutool.core.util.StrUtil;
import com.medusa.gruul.common.core.annotation.EscapeLogin;
import com.medusa.gruul.common.core.auth.client.context.UserExtendsContextHolder;
import com.medusa.gruul.common.core.auth.client.helper.ISecurity;
import com.medusa.gruul.common.core.auth.model.User;
import com.medusa.gruul.common.core.auth.model.UserExtends;
import com.medusa.gruul.common.core.auth.model.constant.Keys;
import com.medusa.gruul.common.core.config.Jackson;
import com.medusa.gruul.common.core.constant.CommonConstants;
import com.medusa.gruul.common.core.constant.enums.AuthCodeEnum;
import com.medusa.gruul.common.core.exception.ServiceException;
import com.medusa.gruul.common.core.helper.RedisKeyHelper;
import com.medusa.gruul.common.redis.RedisManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.NonNull;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * token 拦截器
 * 解析token,把结果存放到 ThreadLocal
 *
 * @author 张治保
 * date 2021/12/2
 */
@Slf4j
public class TokenInterceptor extends HandlerInterceptorAdapter {


    private static final String ASSEMBLE_KEY = "Assemble:";
    private static final String AGENT_KEY = "platfrom:agent:";

    @Override
    public boolean preHandle(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull Object handler) {

        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            EscapeLogin escapeLogin = handlerMethod.getMethodAnnotation(EscapeLogin.class);
            if (escapeLogin != null) {
                return true;
            }
        }
        User user = ISecurity.user().can();
        RedisManager redis = RedisManager.getInstance();
        if (user != null) {
            String userExtendStr = redis.get(RedisKeyHelper.key(Keys.USER_EXTENDS, user.getUserId()));
            if (StrUtil.isNotBlank(userExtendStr)) {
                UserExtendsContextHolder.set(Jackson.readValue(userExtendStr, UserExtends.class));
            }
            return true;
        } else {
            String token = request.getHeader(CommonConstants.TOKEN);
            if (StrUtil.isNotBlank(token)) {
                String userFromToken = redis.get(token);
                if (StrUtil.isNotBlank(userFromToken)) {
                    return true;
                }
                if (StrUtil.isNotBlank(redis.get(ASSEMBLE_KEY + token)) || StrUtil.isNotBlank(redis.get(AGENT_KEY + token))) {
                    return true;
                }
            }
        }
        log.error("认证失败:{}",request.getRequestURI());
        throw new ServiceException(AuthCodeEnum.AUTH_FAIL.getDescription(), AuthCodeEnum.AUTH_FAIL.getType());
    }


}
